package de.eridea.learning.java.usermanagement.logic.pwdverification;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

public class NativeMessageDigest implements PasswordHashFunction {
	private String identifier;
	private MessageDigest messageDigest;
	private static char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7',
			'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public NativeMessageDigest(String algorithm)
			throws NoSuchAlgorithmException {
		messageDigest = MessageDigest.getInstance(algorithm);
		identifier = "tag:frabru.de,2011:pwdhashfunction:native:" + messageDigest.getAlgorithm().toUpperCase(Locale.ROOT);
	}

	public String getIdentifier() {
		return identifier;
	}

	public PasswordDigest digest(Password password) {
		char[] pwd = password.getCharacters();
		byte[] utf16 = new byte[pwd.length * 2];
		for (int k = 0; k < pwd.length; k++) {
			utf16[2 * k] = (byte) ((pwd[k] & 0xFF00) >> 8);
			utf16[2 * k + 1] = (byte) (pwd[k] & 0x00FF);
		}
		password.erase();
		pwd = null;
		byte[] digest = messageDigest.digest(utf16);
		for(int k = 0; k < utf16.length; k++) {
			utf16[k] = 0;
		}
		utf16 = null;
		char[] hex = new char[digest.length * 2];
		for(int k = 0; k < digest.length; k++) {
			hex[2 * k] = hexDigit[(digest[k] & 0xF0)>>4];
			hex[2 * k + 1] = hexDigit[digest[k] & 0x0F];
		}
		return new PasswordDigest(identifier, String.valueOf(hex));
	}
}
